//
//  NSManagedObject+SLSDK.m
//  SLTool
//
//  Created by SongLian on 16/8/6.
//  Copyright © 2016年 SongLian. All rights reserved.
//

#ifdef SLCoreDataResource

#import "NSManagedObject+SLSDK.h"

@interface SLCoreDataHelper : NSObject

//  保存数据
+ (void)saveContext;
//  增
+ (NSManagedObject *)insertNewObjectWithEntityClass:(Class)entityClass;
//  查
+ (NSArray *)readDatasWithEntityClass:(Class)entityClass byValue:(id)value forKey:(NSString *)key;
//  删
+ (void)deleteObjects:(NSArray *)objects;

@end

@implementation NSManagedObject (SLSDK)

+ (void)sl_saveContext {
    [SLCoreDataHelper saveContext];
}

+ (NSArray *)sl_readAllData {
    return [SLCoreDataHelper readDatasWithEntityClass:self byValue:nil forKey:nil];
}

+ (__kindof NSManagedObject *)sl_insertNewObject {
    return [SLCoreDataHelper insertNewObjectWithEntityClass:self];
}

+ (NSArray *)sl_readDatasWithValue:(id)value forKey:(NSString *)key {
    return [SLCoreDataHelper readDatasWithEntityClass:self byValue:value forKey:key];
}

+ (void)sl_deleteObjects:(NSArray *)objects {
    [SLCoreDataHelper deleteObjects:objects];
}

+ (void)sl_deleteObject:(id)object {
    [SLCoreDataHelper deleteObjects:@[object]];
}

@end

@interface SLCoreDataHelper ()

@property (strong, nonatomic) NSManagedObjectContext *objectContext;

@end

@implementation SLCoreDataHelper

+ (instancetype)sharedCoreDataHelper {
    static SLCoreDataHelper *coreDataHelper;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        coreDataHelper = [[SLCoreDataHelper alloc] init];
    });
    return coreDataHelper;
}

- (NSManagedObjectContext *)objectContext {
    
    if (!_objectContext) {
        NSManagedObjectModel *objectModel = [self configObjectModel];
        NSPersistentStoreCoordinator *storeCoordinator = [self configCoordinatorWithObjectModel:objectModel];
        
        _objectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
        _objectContext.persistentStoreCoordinator = storeCoordinator;
    }
    return _objectContext;
}

- (NSManagedObjectModel *)configObjectModel {
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:SLCoreDataResource withExtension:@"momd"];
    NSManagedObjectModel *objectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return objectModel;
}

- (NSPersistentStoreCoordinator *)configCoordinatorWithObjectModel:(NSManagedObjectModel *)objectModel {
    NSPersistentStoreCoordinator *storeCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:objectModel];
    NSURL *storeURL = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask].lastObject;
    storeURL = [storeURL URLByAppendingPathComponent:[SLCoreDataResource stringByAppendingString:@".sqlite"]];
    [storeCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:nil];
    return storeCoordinator;
}

+ (void)saveContext {
    if ([[SLCoreDataHelper sharedCoreDataHelper].objectContext hasChanges])
        [[SLCoreDataHelper sharedCoreDataHelper].objectContext save:nil];
}

+ (NSArray *)readDatasWithEntityClass:(Class)entityClass byValue:(id)value forKey:(NSString *)key {
    
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:NSStringFromClass(entityClass)];
    
    if (value && key) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@ = %@", key, value];
        fetchRequest.predicate = predicate;
    }
    
    NSError *error = nil;
    NSArray *fetchedObjects = [[SLCoreDataHelper sharedCoreDataHelper].objectContext executeFetchRequest:fetchRequest error:&error];
    
    if (error)
        NSLog(@"SLCoreData readDatas error: %@", error);
    
    return fetchedObjects;
}

+ (NSManagedObject *)insertNewObjectWithEntityClass:(Class)entityClass{
    NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass(entityClass) inManagedObjectContext:[SLCoreDataHelper sharedCoreDataHelper].objectContext];
    return object;
}

+ (void)deleteObjects:(NSArray *)objects {
    NSManagedObjectContext *objectContext = [SLCoreDataHelper sharedCoreDataHelper].objectContext;
    for (id object in objects)
        [objectContext deleteObject:object];
}

@end

#endif